package com.liandu.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liandu.common.parent.ParentService;
import com.liandu.common.utils.EncodeUtil;
import com.liandu.dao.CalInfoDao;
import com.liandu.dao.WeighInfoDao;
import com.liandu.entity.CalInfo;
import com.liandu.entity.EcrInfo;
import com.liandu.entity.WeighInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Configuration
@Slf4j
@PropertySource("classpath:application.properties")
//@ConfigurationProperties(prefix = "gy")
public class HashScheduled extends ParentService {
    private static volatile boolean flag = true;

    @Resource
    private OkHttpClient okHttpClient;

    @Value("${gy.blockChain.address}")
    private String url;

    @Scheduled(fixedDelay = 5000) //2秒查询一次
    public void saveHashForWeight() throws IOException {
        if (!flag) {
            return;
        }
        flag = false;
        List<WeighInfo> weighInfoList = weighInfoDao.findAllByTraHashIsNullOrderByInsertDateTimeDesc();//实际使用
        if (weighInfoList.isEmpty()) {
            return;
        }
        Map<String, EcrInfo> ecrInfoMap = ecrInfoDao.findAllById(weighInfoList.stream().map(WeighInfo::getUploadDevice).collect(Collectors.toSet()))
                .stream().collect(Collectors.toMap(EcrInfo::getEcrID, Function.identity()));
        JSONObject jsonObject = null;
        EcrInfo ecrInfo;
//        String type;
        JSONArray jsonArray = new JSONArray();
        for (WeighInfo weighInfo : weighInfoList) {
            ecrInfo = ecrInfoMap.get(weighInfo.getUploadDevice());
            jsonObject = new JSONObject();
            jsonObject.put("key",weighInfo.getID());
            jsonObject.put("unitPrice",weighInfo.getUnitePrice());
            jsonObject.put("weight",weighInfo.getWight());
            jsonObject.put("totalPrice",weighInfo.getPrice());
            jsonObject.put("txNumber",weighInfo.getBillId());
            jsonObject.put("marketName",ecrInfo.getBusiInfo().getMarket().getMarketName());
            jsonObject.put("ecrNumber",ecrInfo.getEcrID());
            jsonObject.put("businessName",ecrInfo.getBusiInfo().getBusiName());
//            switch (ecrInfo.getClassifyType()){
//                case 0:
//                    type = "不识别";
//                    break;
//                case 1:
//                    type = "蔬菜";
//                    break;
//                case 2:
//                    type = "肉类";
//                    break;
//                case 3:
//                    type = "水产";
//                    break;
//                case 4:
//                    type = "杂货";
//                    break;
//                case 5:
//                    type = "干水产";
//                    break;
//                    default:
//                        type = "水果";
//                        break;
//            }
            jsonObject.put("identification",weighInfo.getGoodsCode());
            jsonObject.put("ecrMac",ecrInfo.getMac().getUniNum());
            jsonArray.add(jsonObject);
        }
        Request request = new Request.Builder()
                .url(url+"/save/list/0")
                .post(RequestBody.create(jsonArray.toJSONString(),MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE)))
                .addHeader("connection", "close")
                .build();
        System.out.println(okHttpClient.callTimeoutMillis());
        okHttpClient.newCall(request).enqueue(new TxCallBack(jsonArray,weighInfoList,weighInfoDao));
//        try {
//            Call call = okHttpClient.newCall(request);
//            Response response = call.execute();
//            JSONObject re = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
//            JSONObject reData = JSONObject.parseObject(re.get("data").toString());
//            System.out.println(reData);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    //标定信息获取hash
    @Scheduled(fixedDelay = 2000) //2秒查询一次
    public void saveHashForCal() {
        List<CalInfo> calInfoList = calInfoDao.findAllByCalHashIsNull();
        if (calInfoList.isEmpty()) {
            return;
        }
        Map<String,EcrInfo> ecrInfoMap = ecrInfoDao.findAllById(calInfoList.stream().map(CalInfo::getEcrID).collect(Collectors.toSet()))
                .stream().collect(Collectors.toMap(EcrInfo::getEcrID,Function.identity()));
        JSONArray jsonArray = new JSONArray();
        for (CalInfo info : calInfoList) {
            EcrInfo ecrInfo = ecrInfoMap.get(info.getEcrID());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("marketName",ecrInfo.getBusiInfo().getMarket().getMarketName());
            jsonObject.put("ecrNumber",ecrInfo.getEcrID());
            jsonObject.put("businessName",ecrInfo.getBusiInfo().getBusiName());
            jsonObject.put("calNum",info.getCalFrequency());
            jsonObject.put("calTime",info.getInsertDateTime().getTime());
            jsonObject.put("ecrMac",ecrInfo.getMac().getUniNum());
            jsonObject.put("key",info.getID());
            jsonArray.add(jsonObject);
        }
        Request request = new Request.Builder()
                .url(url+"/save/list/1")
                .post(RequestBody.create(jsonArray.toJSONString(),MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE)))
                .addHeader("connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new CalCallBack(jsonArray,calInfoList,calInfoDao));
    }

    public static class CalCallBack implements Callback{
        private JSONArray jsonArray;
        private List<CalInfo> calInfoList;
        private CalInfoDao calInfoDao;

        public CalCallBack(JSONArray jsonArray, List<CalInfo> calInfoList, CalInfoDao calInfoDao) {
            this.jsonArray = jsonArray;
            this.calInfoList = calInfoList;
            this.calInfoDao = calInfoDao;
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            log.error("errot data ==> {}",jsonArray);
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            JSONObject re = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
            JSONObject reData = JSONObject.parseObject(re.get("data").toString());
            for (CalInfo calInfo : calInfoList) {
                calInfo.setCalHash(reData.getString(calInfo.getID().toString()));
            }
            calInfoDao.saveAll(calInfoList);
        }
    }


    public static class TxCallBack implements Callback{
        private JSONArray jsonArray;
        private List<WeighInfo> weighInfoList;
        private WeighInfoDao weighInfoDao;

        public TxCallBack(JSONArray jsonArray, List<WeighInfo> weighInfoList, WeighInfoDao weighInfoDao) {
            this.jsonArray = jsonArray;
            this.weighInfoList = weighInfoList;
            this.weighInfoDao = weighInfoDao;
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            log.error("errot data ==> {}",jsonArray.size());
            e.printStackTrace();
            HashScheduled.flag = true;
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            JSONObject re = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
            JSONObject reData = re.getJSONObject("data");
            for (WeighInfo weighInfo : weighInfoList) {
                weighInfo.setTraHash(reData.getString(weighInfo.getID().toString()));
            }
            weighInfoDao.saveAll(weighInfoList);
            HashScheduled.flag = true;
        }
    }
}
